package com.emip.dao.impl;

import java.util.List;

import org.springframework.stereotype.Repository;

import com.emip.bean.YearStoreBean;
import com.emip.dao.YearStoreDAO;


@Repository("yearStoreDAO")
public class YearStoreDAOImpl extends StoreDAO implements YearStoreDAO {

	public List<YearStoreBean> getByTimespan(int startYear, int endYear) {
		return this.getByTimespan(startYear, endYear, null, null);
	}

	@SuppressWarnings("unchecked")
	public List<YearStoreBean> getByTimespan(int startYear, int endYear, String[] items, String siteId) {
		String hql = this.getYearHQL(startYear, endYear, items, siteId);
		hql += ", entity.item.id";
		return this.getHibernateTemplate().find(hql);
	}

	public YearStoreBean merge(YearStoreBean store) {
		return getHibernateTemplate().merge(store);
	}

	@SuppressWarnings("unchecked")
	public YearStoreBean findByYear(String year, String siteId, String itemId) {
		List<YearStoreBean> years = 
				getHibernateTemplate().find("from YearStoreBean y where y.year = '" + year + "' and y.site.id = '" + siteId + "' and y.item.id = '" + itemId + "'");
		if (years != null && years.size() > 0) return years.get(0);
		return null;
	}

	public long getCount(int startYear, int endYear, String[] items, String siteId) {
		String hql = "select count(distinct entity.year) " + 
				getYearHQL(startYear, endYear, items, siteId);
		return (Long) getCount(hql);
	}

	public List<YearStoreBean> getByTimespan(int startYear, int endYear,
			String[] itemIds, String siteId, int page, int size) {
		return this.getThPage(YearStoreBean.class, null, startYear, 0, endYear, 0, itemIds, siteId, page, size);
	}

	public Object[] getStatistics(int startYear, int endYear, String itemIds, String siteId) {
		long count = this.getCount(startYear, endYear, new String[]{itemIds}, siteId);
		if (count == 0) return null;
		String[] result = this.getThStatistic("Year", null, startYear, 0, endYear, 0, new String[]{itemIds}, siteId);
		result[3] = Integer.parseInt(result[3])*100/count + "%";
		return result;
	}
}
